
package com.unionServer.gateway;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public final class Server {

    @Value("${tcpServer.port}")
    private int LOCAL_PORT ;

    @Value("${clientServer.ip}")
    private String REMOTE_HOST ;
    @Value("${clientServer.port}")
    private int REMOTE_PORT ;

    public void start() throws Exception {


        log.info("Initializing the gateway :" + LOCAL_PORT + " to " + REMOTE_HOST + ':' + REMOTE_PORT + " ...");

        // Configure the bootstrap.
        final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        final EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new FrontEndInitializer());

            b.bind(LOCAL_PORT).sync();


        } catch (Exception e){
            log.error("Exception occurred while bootstrapping", e);
        }

        new GatewaySender(workerGroup, REMOTE_HOST, REMOTE_PORT);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("Shutting down the Server...");
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                System.out.println("Server successfully terminated");
            }
        });
    }
}
